import { PlusOutlined } from "@ant-design/icons";
import { Button, message, Divider, Popconfirm, Modal, Table } from "antd";
import React, { useState, useRef, useEffect } from "react";
import { FormattedMessage } from "umi";
import { PageContainer } from "@ant-design/pro-layout";
import ProTable from "@ant-design/pro-table";
import { getList, removeField, cmsColumnAllTree } from "./api";
import UpdateForm from "./components/UpdateForm";
import { values } from "lodash";

const setList = (arr) => {
  const newTreeData = [];
  arr.map((item) => {
    const obj = { ...item };

    if (item.children && item.children.length) {
      obj.children = setList(item.children);
    } else {
      obj.children = null;
    }
    newTreeData.push(obj);
    return "";
  });
  return newTreeData;
};

const TableListA = (props) => {
  const { visible, onCancel, data } = props;

  const [columnData, setColumnData] = useState();
  const [columnids, setColumnids] = useState([]);
  const [currentIndex, setCurrentIndex] = useState(0); // 默认排序

  //  加载主数据
  const getData = () => {
    const hide = message.loading("正在加载数据");

    cmsColumnAllTree(data.siteId).then((res) => {
      hide();
      if (res.code === 0) {
        const newData = setList(res.data || []);
        setCurrentIndex(res.data.length);
        setColumnData(newData);
      } else {
        message.error(res.msg);
        setCurrentIndex(0);
      }
    });
  };

  useEffect(() => {
    setColumnids();
    setColumnData();
    if (visible === true) {
      getData();
    }
  }, [visible]);

  const handleCancel = () => {
    onCancel(false);
  };

  // 添加栏目
  const addColumn = () => {
    setType("add");
    setUpdataData({});
    handleUpdateModalVisible(true);
  };
  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param selectedRows
   */
  const handleRemove = async (id) => {
    if (!id || id.length === 0) {
      message.error("请选择删除项");
      return;
    }
    const hide = message.loading("正在删除");
    const payload = { siteId: data.siteId, columnIds: id };
    try {
      const msg = await removeField(payload);
      hide();
      if (msg.code === 0) {
        message.success("删除成功！");
        getData();
        return true;
      }
      message.error(msg.msg || "删除失败，请重试");
      return false;
    } catch (error) {
      hide();
      message.error("删除失败，请重试");
      return false;
    }
  };

  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      const arr = [];
      selectedRows.map((item) => {
        arr.push(item.columnId);
        return "";
      });
      setColumnids(arr);
    },
  };

  const delColumn = () => {
    handleRemove(columnids);
  };

  // 更新数据 组件 ------------------------------------------------------------------

  const [type, setType] = useState();

  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
  const [updataData, setUpdataData] = useState({});

  const closeUpdateForm = () => {
    handleUpdateModalVisible(false);
  };

  const setUpdateForm = (param, index) => {
    setType("updata");
    handleUpdateModalVisible(true);
    param.index = index;
    setUpdataData(param);
  };

  const updataSuccess = () => {
    getData();
  };

  // ----------------------------------------------结束------------------------------------------------------

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */

  const columns = [
    {
      title: "序号",
      valueType: "option",
      dataIndex: "",
      render(text, record, index) {
        return <span key={index}>{index + 1}</span>;
      },
    },
    {
      title: "栏目名称",
      dataIndex: "columnName",
    },
    {
      title: "操作",
      dataIndex: "opt",
      valueType: "option",
      render: (_, record, index) => {
        const text = (
          <>
            <Button type="link" onClick={() => setUpdateForm(record, index)}>
              编辑
            </Button>
            <Divider type="vertical" />
            <Popconfirm
              placement="topRight"
              title="确实要删除此条信息吗？"
              onConfirm={() => handleRemove([record.columnId])}
              okText="确定"
              cancelText="取消"
            >
              <Button type="link">删除</Button>
            </Popconfirm>
          </>
        );
        return <>{text}</>;
      },
    },
  ];
  return (
    <>
      <Modal
        visible={visible}
        maskClosable={false}
        title={`${data?.siteName}-栏目`}
        onOk={handleCancel}
        onCancel={handleCancel}
        width={900}
        footer={null}
      >
        <div style={{ textAlign: "right", marginTop: 0, marginBottom: 20 }}>
          <Popconfirm
            placement="topRight"
            title="确实要删除多栏目吗？"
            onConfirm={delColumn}
            okText="确定2"
            cancelText="取消"
          >
            <Button>删除</Button>
          </Popconfirm>

          <Button type="primary" style={{ marginLeft: 20 }} onClick={addColumn}>
            新建
          </Button>
        </div>
        <Table
          columns={columns}
          dataSource={columnData}
          rowKey={(record) => record.columnId}
          rowSelection={{ ...rowSelection }}
          pagination={false}
        />
        <div style={{ textAlign: "right", marginTop: 20 }}>
          <Button onClick={handleCancel}>取消</Button>
        </div>
        {updateModalVisible === true && (
          <UpdateForm
            visible={updateModalVisible}
            onCancel={closeUpdateForm}
            data={updataData}
            siteId={data.siteId}
            currentIndex={currentIndex}
            onSuccess={updataSuccess}
            type={type}
          />
        )}
      </Modal>
    </>
  );
};

export default TableListA;
